package com.iqiyi.pps.epg.core.service.reservation;

import com.iqiyi.pps.epg.api.model.web.reservation.TReservation;
import com.iqiyi.pps.epg.core.dao.base.Page;
import com.iqiyi.pps.epg.core.dao.base.PropertyFilter;
import com.iqiyi.pps.epg.core.dao.reservation.ReserveControlDao;
import com.iqiyi.pps.epg.core.model.reservation.ReserveControl;
import org.hibernate.SQLQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class ReservationServiceImpl implements ReservationService {
    private static Logger logger = LoggerFactory.getLogger(ReservationService.class);

    @Autowired
    private ReserveControlDao reserveControlDao;

    @Override
    public ReserveControl getById(long id) {
        return reserveControlDao.get(id);
    }

    /**
     * 批量添加预约，成功返回1，失败返回0，时间段重复返回-1
     * @param entities
     * @return
     */
    @Override
    public int add(List<TReservation> entities) {
        try {
            // 去重
            String sql = "select count(*) from reserve_channel where father_id = :fatherId and (" +
                "(start_time >= :startTime and start_time <= :endTime) or (start_time <= :startTime and end_time >= :startTime)" +
                ") and platform = :platform and status < 9";
            // Query query = reserveControlDao.getSession().createQuery(sql);
            SQLQuery query = reserveControlDao.getSession().createSQLQuery(sql);
            for (TReservation item : entities) {
                Object obj = query.setParameter("fatherId", item.getFatherId())
                    // .setParameter("startTime", item.getStartTime(), new TimestampType())
                    .setParameter("startTime", item.getStartTime())
                    .setParameter("endTime", item.getEndTime())
                    .setParameter("platform", item.getPlatform())
                    .uniqueResult();
                if (Integer.valueOf(obj.toString()) > 0) {
                    return -1;
                }
            }
            for (TReservation item : entities) {
                ReserveControl model = ReserveControl.thriftToEntity(item);
                reserveControlDao.save(model);
            }
        } catch (Exception e) {
            return 0;
        }
        return 1;
    }

    @Override
    public boolean save(ReserveControl entity) {
        try {
            reserveControlDao.save(entity);
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    @Override
    public boolean del(long id) {
        try {
            // reserveControlDao.delete(id);
            ReserveControl entity = getById(id);
            if (entity != null) {
                entity.setStatus(ReserveControl.STATUS_DELETE);
                return save(entity);
            }
        } catch (Exception e) {
            logger.info("[ReservationServiceImpl][del][error={}]", e);
        }
        return false;
    }

    @Override
    public boolean delByChannelId(long channelId) {
        try {
            String hql = "update ReserveControl set status = ? where fatherId = ?";
            reserveControlDao.batchExecute(hql, ReserveControl.STATUS_DELETE, channelId);
            return true;
        } catch (Exception e) {
            logger.info("[ReservationServiceImpl][delByChannelId][error={}]", e);
        }
        return false;
    }

    @Override
    public Page<ReserveControl> get(Page<ReserveControl> page, List<PropertyFilter> filters) {
        return reserveControlDao.findPage(page, filters);
    }

    @Override
    public List<ReserveControl> getDataByTime(int timeType, String startTime, String endTime) {
        String column, status;
        if (timeType == ReservationService.IS_END_TIME) {
            column = "end_time";
            status = " status < " + ReserveControl.STATUS_RENEW_SUCCESS + " and status >= " + ReserveControl.STATUS_ENABLE_SUCCESS;
        } else {
            column = "start_time";
            status = " status < " + ReserveControl.STATUS_ENABLE_SUCCESS;
        }
        String sql = "select * from `reserve_channel` where `" + column + "` between '" + startTime + "' and '" + endTime + "' and " + status;
        logger.info("[ReservationServiceImpl][getDataByTime][sql={}]", sql);
        return reserveControlDao.getSession()
            .createSQLQuery(sql)
            .addEntity(ReserveControl.class)
            .list();
    }

    /**
     * 获取频道下当前分钟预约中的播控预约
     * @param channelId
     * @return
     */
    @Override
    public List<ReserveControl> getCurrentMinuteDataByChannelId(long channelId) {
        String sql = "select * from `reserve_channel` where `father_id` = " + channelId
            + " and `start_time` <= date_format(now(), '%Y-%m-%d %H:%i:00') and `end_time` > date_format(now(), '%Y-%m-%d %H:%i:59') and `status` < 5 and `type` = 1";
        logger.info("[ReservationServiceImpl][getCurrentMinuteDataByChannelId][sql={}]", sql);
        return reserveControlDao.getSession()
            .createSQLQuery(sql)
            .addEntity(ReserveControl.class)
            .list();
    }
}
